package quartz_exercise.connectmysql.service.impl;

import lombok.SneakyThrows;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import quartz_exercise.connectmysql.config.MyTask01;
import quartz_exercise.connectmysql.config.MyTask02;
import quartz_exercise.connectmysql.mapper.ConnectMapper;
import quartz_exercise.connectmysql.service.ConnectService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ConnectServiceImpl implements ConnectService {

    @Autowired
    private ConnectMapper connectMapper;

    @SneakyThrows
    @Override
    public String beginTask() {

        SchedulerFactory sf= new StdSchedulerFactory();
        Scheduler scheduler = sf.getScheduler();
        Date nowDate = new Date();
        Date beginTime= new Date(nowDate.getTime()+3000);
        Date endTime=new Date(nowDate.getTime()+6000);

        Date beginTime02= new Date(nowDate.getTime()+12000);
        Date endTime02= new Date(nowDate.getTime()+16000);

        List<Date> dateList=new ArrayList<>();
        dateList.add(beginTime);
        dateList.add(endTime);
        dateList.add(beginTime02);
        dateList.add(endTime02);
        String[] crons={
                "0 17 13 * * ? *","20 17 13 * * ? *","0 18 13 * * ? *","10 18 13 * * ? *"
        };

        for (String cron:crons){

            JobDetail jobDetail= JobBuilder.newJob(MyTask01.class).build();
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            Trigger trigger=TriggerBuilder.newTrigger()
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();


            scheduler.scheduleJob(jobDetail,trigger);

            scheduler.start();

        }


//
//        for (Date date:dateList){
//
//            JobDetail jobDetail= JobBuilder.newJob(MyTask01.class).build();
//            JobDataMap jobDataMap = jobDetail.getJobDataMap();
//            jobDataMap.put("beginTime",date);
//            Trigger trigger=TriggerBuilder.newTrigger()
//                    .startAt(date)
//                    .build();
//
//
//            scheduler.scheduleJob(jobDetail,trigger);
//
//            scheduler.start();
//
//        }

        return "定时任务已经启动";

    }

    @SneakyThrows
    @Override
    public String endTask() {
        StdSchedulerFactory sf = new StdSchedulerFactory();
        Scheduler scheduler = sf.getScheduler();

        JobDetail jobDetail = JobBuilder.newJob(MyTask02.class)
                .build();


        Trigger trigger=TriggerBuilder.newTrigger()
                .startNow()
                .build();

        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();

        return "结束完成";

    }
}
